﻿// TabPanel的Carousel功能插件
Ext.define('ux.plugin.SwipeTabs', {
	alias : 'plugin.swipetabs',
	xtype : 'swipetabs',
	id : 'swipetabs',
	config : {
		cmp : null,
		// 是否循环滚动
		allowOverflow : false,
		// 是否允许滑动切换
		allowSwipe : false,
		animation : {
			duration : 300,
			easing : 'ease-out',
			type : 'slide'
		}
	},
	constructor : function(config) {
		this.initConfig(config);
		this.callParent([config]);
	},
	init : function(cmp) {
		this.setCmp(cmp);
	},
	updateCmp : function(newCmp, oldCmp) {
		if (oldCmp) {
			oldCmp.element.un('swipe', this.onSwipe);
		}
		if (newCmp) {
			newCmp.element.on('swipe', this.onSwipe, this);
		}
	},
	onSwipe : function(e) {
		if(this.getAllowSwipe()==false){
			return;
		}
		var cmp = this.getCmp(), allowOverflow = this.getAllowOverflow(),
		// 获取切换动画效果
		animation = this.getAnimation(),
		// 滑动方向
		direction = e.direction,
		// 当前选中项
		activeItem = cmp.getActiveItem(),
		// 所有项
		innerItems = cmp.getInnerItems(),
		// 最大索引
		numIdx = innerItems.length - 1,
		// 当前选中项索引
		idx = Ext.Array.indexOf(innerItems, activeItem),
		// 目标索引
		newIdx = idx + (direction === 'left' ? 1 : -1), newItem;
		// 处理目标索引，避免出错
		if (newIdx < 0) {
			if (allowOverflow) {
				newItem = innerItems[numIdx];
				newIdx = numIdx;
			}
		} else if (newIdx > numIdx) {
			if (allowOverflow) {
				newItem = innerItems[0];
				newIdx = 0;
			}
		} else {
			newItem = innerItems[newIdx];
		}
		if (newItem) {
			animation = Ext.apply({}, {
						direction : direction
					}, animation);
			// 切换
			cmp.animateActiveItem(newItem, animation);
			// 设置导航滚动
			var mun = cmp.getMoveNum();
			if (mun && mun > 0) {
				var scr = cmp.getTabBar().getScrollable().getScroller();
				scr.scrollTo(newIdx * mun, 0);
			}
		}
	}
});